package cn.enilu.guns.admin.modular.door;

import cn.enilu.guns.admin.common.constant.device.TableConstant;
import cn.enilu.guns.admin.core.base.tips.SetDataToDeviceTip;
import cn.enilu.guns.admin.equipment.dto.UserauthorizeDto;
import cn.enilu.guns.bean.entity.door.DoorInfo;
import cn.enilu.guns.bean.entity.door.EntranceGuardDoor;
import cn.enilu.guns.bean.entity.door.EntranceGuardRule;
import cn.enilu.guns.admin.equipment.service.EntranceGuardService;
import cn.enilu.guns.bean.entity.door.UserCard;
import cn.enilu.guns.business.DoorBusiness;
import cn.enilu.guns.service.door.DoorInfoService;

import cn.enilu.guns.bean.annotion.core.BussinessLog;
import cn.enilu.guns.bean.constant.factory.PageFactory;
import cn.enilu.guns.bean.dictmap.CommonDict;
import cn.enilu.guns.admin.core.base.controller.BaseController;

import cn.enilu.guns.bean.vo.query.Page;
import cn.enilu.guns.bean.vo.query.SearchFilter;


import cn.enilu.guns.service.door.EntranceGardUserService;
import cn.enilu.guns.service.door.EntranceGuardDoorService;
import cn.enilu.guns.service.door.EntranceGuardRuleService;
import cn.enilu.guns.service.system.impl.ConstantFactory;
import cn.enilu.guns.utils.BeanUtil;
import cn.enilu.guns.utils.Lists;
import cn.enilu.guns.warpper.door.DoorInfoWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/door/DOOR/INFO")
public class DoorInfoController extends BaseController {
	private  Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private DoorInfoService doorInfoService;
	@Autowired
	private EntranceGuardDoorService entranceGuardDoorService;
	@Autowired
	private EntranceGuardRuleService entranceGuardRuleService;
	@Autowired
	private DoorBusiness doorBusiness;
	@Autowired
	private EntranceGuardService entranceGuardService;
	@Autowired
	private EntranceGardUserService entranceGardUserService;

	private static String PREFIX = "/door/DOOR/INFO/";

	/**
	* 跳转到首页
	*/
	@RequestMapping(value="",method = RequestMethod.GET)
		public String index() {
		return PREFIX + "index.html";
	}

	/**
	* 跳转到添加页面
	*/
	@RequestMapping(value = "/add",method = RequestMethod.GET)
		public String add() {
		return PREFIX + "add.html";
	}

	/**
	* 跳转到修改页面
	*/
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable Long id, Model model) {
		DoorInfo entity = doorInfoService.get(id);
		model.addAttribute("item",entity);
        model.addAttribute("areaName", ConstantFactory.me().getAreaName(Integer.valueOf(entity.getAreaId().toString())));
		return PREFIX + "edit.html";
	}
	@RequestMapping(value = "/list",method = RequestMethod.POST)
	@ResponseBody
	public Object list(@RequestParam(required = false) String doorName) {
		Page<DoorInfo> page = new PageFactory<DoorInfo>().defaultPage();
		page.addFilter("doorName", SearchFilter.Operator.EQ,doorName);
		page = doorInfoService.queryPage(page);
        Page<Object> pageEquipmentInfoWarpper =  new PageFactory<Object>().defaultPage();
        BeanUtils.copyProperties(page,pageEquipmentInfoWarpper);
        pageEquipmentInfoWarpper.setRecords((List<Object>) new DoorInfoWarpper(BeanUtil.objectsToMaps(page.getRecords())).warp());
		return super.packForBT(pageEquipmentInfoWarpper);
	}

	/**
	 * 获取所有门
	 */
	@RequestMapping(value = "/getDoorList")
	@ResponseBody
	public Object getDoorList(@RequestParam(required = false) Long id) {
		List<SearchFilter> searchFilters = Lists.newArrayList();
		List<DoorInfo> doorInfos = doorInfoService.queryAll(searchFilters, new Sort(Sort.Direction.ASC, "id"));
		return doorInfos;
	}
	/**
	* 新增门信息
	*/
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	@ResponseBody
	@BussinessLog(value = "新增门信息", key = "name",dict= CommonDict.class)
	public Object add(DoorInfo doorInfo) {
		doorInfoService.insert(doorInfo);
		return SUCCESS_TIP;
	}

	/**
	* 删除门信息
	*/
	@RequestMapping(value = "/delete")
	@ResponseBody
	@BussinessLog(value = "删除门信息", key = "id",dict= CommonDict.class)
	public Object delete(@RequestParam Long id) {
		doorInfoService.delete(id);
		return SUCCESS_TIP;
	}

	/**
	* 修改门信息
	*/
	@RequestMapping(value = "/update")
	@ResponseBody
	@BussinessLog(value = "修改门信息", key = "name",dict= CommonDict.class)
	public Object update(DoorInfo doorInfo) {
		doorInfoService.update(doorInfo);
		return SUCCESS_TIP;
	}
	/**
	 * 跳转到分配权限页面
	 */
	@RequestMapping("/setRuleToDoor/{id}")
	public String setRuleToDoor(@PathVariable Long id, Model model) {
		DoorInfo entity = doorInfoService.get(id);
		model.addAttribute("item",entity);
//		logger.info("------------------"+entity.getUsers().toString());
		return PREFIX + "setRuleToDoor.html";
	}
	/**
	 * 获取门已设置的门禁权限
	 */
	@RequestMapping(value = "/selectRulesForDoor")
	@ResponseBody
	public Object selectRulesForDoor(@RequestParam(required = false) Long id) {
		return doorBusiness.getEntranceGuardRules(id);
	}

	/**
	 * 设置门禁权限
	 * @param doorInfo
	 * @param idsArr
	 * @return
	 */
	@RequestMapping(value = "assignRule")
	@ResponseBody
	@BussinessLog(value = "设置门禁权限", key = "name",dict= CommonDict.class)
	public Object assignRule(DoorInfo doorInfo, String[] idsArr) {

		doorInfo = doorInfoService.get(doorInfo.getId());
        //生成已经分配的权限Map
		Map<String ,EntranceGuardRule> oldEntranceGuardRuleMap = new HashMap<>();
		List<EntranceGuardRule> entranceGuardRules = doorBusiness.getEntranceGuardRules(doorInfo.getId());
		for (EntranceGuardRule entranceGuardRule:entranceGuardRules) {
			oldEntranceGuardRuleMap.put(doorInfo.getId()+"_" + entranceGuardRule.getId(),entranceGuardRule);
		}
		//新添加的分配的权限
		List<EntranceGuardRule> addEntranceGuardRules = Lists.newArrayList();
		//需要删除的权限
		List<EntranceGuardRule> removeEntranceGuardRules = Lists.newArrayList();
		//最新存储权限
		Map<String ,String> newEntranceGuardRuleMap = new HashMap<>();
		for (int i = 0; i < idsArr.length; i++) {
			if(!oldEntranceGuardRuleMap.containsKey(doorInfo.getId()+ "_" + idsArr[i])) {
				EntranceGuardDoor entranceGuardDoor = new EntranceGuardDoor();
				entranceGuardDoor.setDoorId(doorInfo.getId());
				entranceGuardDoor.setEquipmentId(doorInfo.getEquipmentInfo().getId());
				entranceGuardDoor.setRuleId(Long.valueOf(idsArr[i]));
				entranceGuardDoorService.insert(entranceGuardDoor);
				addEntranceGuardRules.add(entranceGuardRuleService.get(Long.valueOf(idsArr[i])));
			}
			newEntranceGuardRuleMap.put(doorInfo.getId()+ "_" + idsArr[i],idsArr[i]);
		}
		for(Map.Entry<String, EntranceGuardRule> entry : oldEntranceGuardRuleMap.entrySet()){
			if(!newEntranceGuardRuleMap.containsKey(entry.getKey())) {
				//删除人员
				List<SearchFilter> searchFilters = Lists.newArrayList();
				searchFilters.add(new SearchFilter("ruleId",SearchFilter.Operator.EQ,entry.getValue().getId()));
				searchFilters.add(new SearchFilter("doorId",SearchFilter.Operator.EQ,doorInfo.getId()));
				List<EntranceGuardDoor> entranceGuardDoors = entranceGuardDoorService.queryAll(searchFilters);
				for (EntranceGuardDoor entranceGuardDoor:entranceGuardDoors) {
					entranceGuardDoorService.delete(entranceGuardDoor.getId());
				}
				removeEntranceGuardRules.add(entry.getValue());
			}
		}


		String strTip = "";
//		//向设备中写入人员信息
		for (EntranceGuardRule entranceGuardRule:addEntranceGuardRules ) {
			//向设备中写入人员信息
			List<UserCard> userCards = entranceGardUserService.getUserAndCardInfoByRuleId(entranceGuardRule.getId());
			entranceGuardService.addDataToDoor(doorInfo, TableConstant.TABLE_USER, userCards);

			//向设备中写入时段
			//todo 根据权限获取时段信息,设置时段信息
			entranceGuardService.addDataToDoor(doorInfo, TableConstant.TABLE_TIMEZONE, entranceGuardRule.getTimeInfo().toString());
			//向设备中写入权限信息
			List<UserauthorizeDto> userauthorizeDtos = Lists.newArrayList();
			for (UserCard userCard : userCards) {
				UserauthorizeDto userauthorizeDto = new UserauthorizeDto();
				userauthorizeDto.setUserId(userCard.getUserInfo().getId());
				//todo 添加时段信息
				userauthorizeDto.setTimeInfoId(entranceGuardRule.getTimeInfo().getId());
				userauthorizeDto.setDoorId(Long.valueOf(doorInfo.getDoorNo()));
				userauthorizeDtos.add(userauthorizeDto);
			}
			entranceGuardService.addDataToDoor(doorInfo, TableConstant.USERAUTHORIZE, userauthorizeDtos);

		}
		//向设备中写入需要删除的人员信息
		for (EntranceGuardRule entranceGuardRule:removeEntranceGuardRules ) {
			//向设备中写入人员信息
			List<UserCard> userCards = entranceGardUserService.getUserAndCardInfoByRuleId(entranceGuardRule.getId());
			entranceGuardService.removeDataFromDoor(doorInfo, TableConstant.TABLE_USER, userCards);

			//向设备中写入时段
			//todo 根据权限获取时段信息,设置时段信息
			entranceGuardService.removeDataFromDoor(doorInfo, TableConstant.TABLE_TIMEZONE, entranceGuardRule.getTimeInfo().toString());
			//向设备中写入权限信息
			List<UserauthorizeDto> userauthorizeDtos = Lists.newArrayList();
			for (UserCard userCard : userCards) {
				UserauthorizeDto userauthorizeDto = new UserauthorizeDto();
				userauthorizeDto.setUserId(userCard.getUserInfo().getId());
				//todo 添加时段信息
				userauthorizeDto.setTimeInfoId(entranceGuardRule.getTimeInfo().getId());
				userauthorizeDto.setDoorId(Long.valueOf(doorInfo.getDoorNo()));
				userauthorizeDtos.add(userauthorizeDto);
			}
			entranceGuardService.removeDataFromDoor(doorInfo, TableConstant.USERAUTHORIZE, userauthorizeDtos);
		}

		SetDataToDeviceTip setDataToDeviceTip = new SetDataToDeviceTip(200,strTip);
		return setDataToDeviceTip;
	}
}